﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TimeTableManagement.Entities;
using System.Web.Security;
using System.Data;
using TimeTableManagement.Models;

namespace TimeTableManagement.Controllers
{
    
    public class AccountController : Controller
    {
        QLSVContext _context = new QLSVContext();
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult LogOn()
        {
            //var model = _context.Tb_Userlogin.ToList();
            return View();
        }
        /// <summary>
        /// Lấy ra ID của User khi nó logon vào hệ thống bằng username
        /// </summary>
        /// <param name="username">Username, tên đăng nhập</param>
        /// <returns>ID kiểu int</returns>
        public int getID(String username)
        {
            var model = _context.Tb_Userlogin.Where(g => g.username.Equals(username)).ToList();
            if(model.Count>0)
            foreach (var item in model)
            {
                return item.id;    
            }
            return -1;
        }
        //
        // POST: /Account/Logon

        [HttpPost]
        public ActionResult LogOn(Tb_Userlogin model, string returnUrl)
        {
            int tam_role = 0;
            if (ModelState.IsValid)
            {
                String _u = model.username;
                //String _p = Functions.Encrypt(model.password);
                String _p = model.password;
                var getuser = _context.Tb_Userlogin.ToList();
                Boolean logonsuccess = false;
                foreach (var item in getuser)
                {
                    if (item.username.Equals(_u) && item.password.Equals(_p))
                    {
                        logonsuccess = true;
                        tam_role = item.id_role;
                    }
                }
                if (logonsuccess == true)
                {
                    try
                    {
                        var peo = _context.Tb_People.Where(g => g.mssv.Equals(model.username));
                        int idpeople = peo.First<Tb_People>().id;
                        String displayname = peo.First<Tb_People>().name;
                        FormsAuthentication.SetAuthCookie(displayname, model.rememberme);
                        Session.Add("USERNAME", model.username);
                        Session.Add("USERID", this.getID(model.username));
                        Session.Add("ROLE", new Tb_Role().getRoleString(tam_role));
                        Session.Add("KEY", Session.SessionID);
                        Session["IDPEOPLE"] = idpeople;
                        LOG.user_infor(model.username, "Da dang nhap vao he thong", "yes");
                    }
                    catch { }
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    
                }
                else
                {
                    LOG.user_infor(model.username, "Dang nhap he thong", "no");
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            return View(model);
        }
        //
        // GET: /Account/LogOff

        public ActionResult Logoff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
        //
        //GET: /Account/InforUserLogin
        [Authorize]
        public ActionResult InforUserLogin()
        {
            int iduser = 0;
            try
            {
                iduser = (int)Session["USERID"];
            }
            catch {
                RedirectToAction("LogOn", "Account");
            }

            var model = _context.Tb_Userlogin.Find(iduser);
            ViewData["rolename"] = model.Tb_Role.rolename;
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                String oldpass = Functions.Encrypt(model.OldPassword);
                int id = (int) Session["USERID"];
                bool changePasswordSucceeded=false;
                var getuser = _context.Tb_Userlogin.Find(id);
                if (getuser.password.Equals(oldpass))
                {
                    getuser.password = Functions.Encrypt(model.NewPassword);
                    _context.SaveChanges();
                    changePasswordSucceeded = true;
                }
                if (changePasswordSucceeded)
                {
                    LOG.user_infor((String)Session["USERNAME"], "Doi mat khau", "yes");
                    ModelState.AddModelError("", "The password is changed succsessfuly.");
                }
                else
                {
                    LOG.user_infor((String)Session["USERNAME"], "Doi mat khau", "no");
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        //POST: /Account/ResetPassword
        public ActionResult ResetPassword()
        {
            ViewData["isreset"] = "no";
            return View();
        }
       
        //
        //POST: /Account/ResetPassword
        [HttpPost]
        public ActionResult ResetPassword(ResetPassword _resetpass)
        {
            if (ModelState.IsValid)
            {
                String newpass = Functions.RandomPassword(8);
                ViewData["yourpass"] = newpass;
                newpass = Functions.Encrypt(newpass);
                bool haveuser = false;
                var getuser = _context.Tb_Userlogin.Where(g => g.username.Equals(_resetpass.username));
                int id=0;
                foreach (var item in getuser)
                {
                    if (item.username.Equals(_resetpass.username) || item.email.Equals(_resetpass.email))
                    {
                        haveuser = true;
                        id = item.id;
                        break;
                    }
                    
                }
                if (haveuser)
                {
                    var u = _context.Tb_Userlogin.Find(id);
                    u.password = newpass;
                    _context.SaveChanges();
                    LOG.user_infor((String)Session["USERNAME"], "Lay lai mat khau", "yes");
                    ViewData["isreset"] = "yes";
                }
                else
                {
                    LOG.user_infor((String)Session["USERNAME"], "Lay lai mat khau", "no");
                    ViewData["isreset"] = "no";
                    ModelState.AddModelError("", "Username and Email that you enter, is not exist.");
                }
                
            }
            return View();
        }


        
        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
